// pages/user/index.js
const app = getApp();

let api = require('../../utils/api.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userData: {},
    dialogShow: false,
    showOneButtonDialog: false,
    buttons: [{
      text: '取消'
    }, {
      text: '确定'
    }],
    oneButton: [{
      text: '确定'
    }],
    code: '',
    sendTime: '发送验证码',
    sendColor: '#363636',
    snsMsgWait: 60,
    isShow: 0
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    var token = wx.getStorageSync('TOKEN');
    var that = this;
    that.setData({
      isLogin: token ? true : false,
    })
    if (token) {
      app.getUserInfo().then((res) => {
        var userData = {};
        var userName = '';
        if (res.nickname != null) {
          userName = res.nickname;
        }
        userData = {
          userName: userName,
          userHead: res.headImg,
          phone: res.phone,
        }
        app.getRemind()

        that.setData({
          userData: userData
        })

      })

    }
  },
  goHome() {
    this.setData({
      showShareModelStatus: false
    })
  },
  /*
   * 分享应用
   */
  showShareModel: function (e) {
    let that = this;
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    that.animation = animation
    animation.translateY(300).step()
    that.setData({
      animationData: animation.export(),
      showShareModelStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      that.setData({
        animationData: animation.export()
      })
    }.bind(that), 200)
  },

  // 隐藏对话框
  hideModal: function () {
    let that = this;
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    that.animation = animation
    animation.translateY(300).step();
    that.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step();
      that.setData({
        animationData: animation.export(),
        showShareModelStatus: false
      })
    }.bind(that), 200)
  },
  //  跳转到  临时页面
  getIndex() {
    wx.navigateTo({
      url: '/pages/user/staytuned/staytuned',
    });
    this.setData({
      showShareModelStatus: false
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    console.log(res);
    if (res.from === 'button') {
      // console.log('来自页面内转发按钮');
      // wx.switchTab({
      //   url: '/pages/index/index'
      // })
      this.setData({
        showShareModelStatus: false
      })
    } else if (res.from === 'menu') {
      console.log(res.from);
      console.log('右上角菜单转发按钮');
    }
  },
  // 编辑昵称
  editUserName: function () {
    this.setData({
      nameDialogShow: true,
    })
  },
  // 编辑电话
  editUserPhone: function () {
    this.setData({
      phoneDialogShow: true
    })
  },
  confromUserName(e) {
    // console.log(e);
    this.setData({
      phoneDialogShow: false,
      nameDialogShow: false,
      showOneButtonDialog: false
    })
  },
  tapOneDialogButton(e) {
    this.setData({
      showOneButtonDialog: true
    })
  },
  /**
   * 禁止输入表情符号
   */
  regStrFn: function (str) {
    let reg = /([^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n])|(\s)/g,
      indexArr = reg.exec(str);
    if (str.match(reg)) {
      str = str.replace(reg, '');
    }
    let obj = {
      val: str,
      index: indexArr
    }
    return obj
  },

  // 输入监听
  inputWacth: function (e) {
    // console.log(e);
    var that = this;
    let item = e.currentTarget.dataset.model;
    let value = e.detail.value;

    // let name = 'form.' + item
    // let val = e.detail.value,
    //   　pos = e.detail.cursor;
    // let reg = /([^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n])|(\s)/g
    // if (!reg.test(val)) {　　
    //   return
    // }

    // let obj = that.regStrFn(val)

    // if (pos != -1 && obj.index) {
    //   // 计算光标的位置
    //   　　
    //   pos = obj.index.index
    // }

    that.setData({
      // [item]: obj.val
      [item]: value
    });
    // return {　　
    //   value: obj.val,
    //   　　cursor: pos
    // }
  },
  // 关闭弹框
  _cancelEvent: function (e) {
    this.setData({
      editPhone: '',
      editNickname: '',
      phoneDialogShow: false,
      nameDialogShow: false,
    });
  },
  // 提交用户名
  _nameConfirmEvent: function (e) {
    var that = this;
    var token = wx.getStorageSync('TOKEN');
    var type = 'nickname';
    var value = that.data.editNickname;
    var search = /(?:(?=.*[0-9].*)(?=.*[A-Za-z].*)(?=.*[\\W].*))[\\W0-9A-Za-z]{8,16}$/;
    var reg = /([\u4E00-\u9FA5])+/; //只要包含中文

    var han = /^[\u4e00-\u9fa5]+$/;

    if (!han.test(value)) {
      // console.log(value);
      // console.log(han.test(value));
      wx.showToast({
        title: '真实姓名，暂不支持字母、数字及符号，请重新输入',
        icon: 'none'
      })
      return;
    }
    var params = {
      dataname: 'userData.userName',
      storageName: 'NICKNAME'
    }
    that.changeUserInfo(type, value, token, params);
  },

  // 提交手机
  _phoneConfirmEvent: function (e) {
    var that = this;
    var token = wx.getStorageSync('TOKEN');
    var type = 'phone';
    var value = that.data.editPhone;
    var code = that.data.code;
    if (value == "") {
      that.toast("手机号不可为空");
      return;
    }
    if (code == "") {
      that.toast("验证码不可为空");
      return;
    }
    var params = {
      dataname: 'userData.phone',
      storageName: 'PHONE'
    }
    that.changeUserInfo(type, value, token, params, code);
  },

  // 修改用户操作
  changeUserInfo: function (type, value, token, params, code) {
    var that = this;
    var param = {
      [type]: value
    }
    if (code) {
      param.verifyCode = code
    }
    api._put('/user/info/edit', param, token).then(res => {
      if (res.code == 200) {
        if (params.imgUrl) {
          value = params.imgUrl
        }
        var item = params.dataname;
        var storageName = params.storage
        that._cancelEvent();
        that.setData({
          [item]: value
        });
        wx.setStorageSync(storageName, value);
      } else if (res.code == 20000013 || res.code == 20000014) {
        wx.showToast({
          title: res.message,
          icon: 'none',
        })
      } else {
        wx.showToast({
          title: '网络忙，请稍后重试',
          icon: 'none',
        })
      }
    })
  },
  /**
   * 修改头像
   */
  changeAvatar: function (e) {
    var _this = this;
    var token = wx.getStorageSync('TOKEN');

    var url = api.baseUrl;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        //这里是上传操作
        wx.uploadFile({
          url: url + '/file/img/upload', //里面填写你的上传图片服务器API接口的路径 
          filePath: tempFilePaths[0], //要上传文件资源的路径 String类型 
          name: 'file', //按个人情况修改，文件对应的 key,开发者在服务器端通过这个 key 可以获取到文件二进制内容，(后台接口规定的关于图片的请求参数)
          header: {
            "Content-Type": "multipart/form-data", //记得设置
            //和服务器约定的token, 一般也可以放在header中
            'token': token
          },

          success: function (res) {
            //当调用uploadFile成功之后，再次调用后台修改的操作，这样才真正做了修改头像
            if (res.statusCode = 200) {
              var data = JSON.parse(res.data);
              // var statusCode = res.statusCode
              // console.log("返回值1" + data);
              var type = 'headImg';
              var value = data.result.id;
              var params = {
                dataname: 'userData.userHead',
                storageName: 'HEADIMG',
                imgUrl: data.result.thumbUrl
              }
              _this.changeUserInfo(type, value, token, params);
              // // console.log("返回值2" + statusCode)
              //这里调用后台的修改操作， tempFilePaths[0],是上面uploadFile上传成功，然后赋值到修改这里。
            }
          }
        })
      }
    })
  },

  // 获取验证码
  sendCode: function () {
    var that = this;

    if (this.data.editPhone == "") {
      this.toast('请输入手机号');
      return;
    } else if (!(/^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(this.data.editPhone))) {
      this.toast('手机号输入错误');
      return;
    } else {
      api._get('/sms/send/' + that.data.editPhone + '/1', '', '').then(res => {
        // console.log(res)
        if (res.code == 200) {

        } else {
          wx.showToast({
            title: '请稍后重试',
            icon: 'none',
          })
        }
      })
      // 60秒后重新获取验证码
      var inter = setInterval(function () {
        this.setData({
          smsFlag: true,
          sendColor: '#cccccc',
          sendTime: this.data.snsMsgWait + 's后重发',
          snsMsgWait: this.data.snsMsgWait - 1
        });
        if (this.data.snsMsgWait < 0) {
          clearInterval(inter)
          this.setData({
            sendColor: '#363636',
            sendTime: '发送验证码',
            snsMsgWait: 60,
            smsFlag: false
          });
        }
      }.bind(this), 1000);

    }

  },

  inputCode: function (e) {
    this.setData({
      code: e.detail.value
    })
  },
  // toast方法抽取
  toast: function (msg) {
    wx.showToast({
      title: msg,
      icon: 'none',
      duration: 2000,
      mask: true
    })
  },


  login() {
    app.goAuthpPages()
  },

  callExpert: function (e) {
    //// console.log(e.currentTarget.dataset.phone)
    var phone = e.currentTarget.dataset.phone;
    app.callExpert(phone);
  },
})